//
//  SearchView.m
//  MobileZIPCodes
//
//  Created by Andreas Schwelling on 29.11.07.
//	http://www.andi.de/zipcodes/
// 
//  Released under the GNU General Public License.
//  See LICENSE for details.
//
//  Use at your own risk.
//

#import "SearchView.h"

#import <Foundation/Foundation.h>
#import <GraphicsServices/GraphicsServices.h>
#import <UIKit/UIKit.h>
#import <UIKit/UIView-Geometry.h>
#import <UIKit/UITextLabel.h>




@implementation UIRightTextLabel

-(void)setFrame:(CGRect)frame{
	[super setFrame:frame];
	if (_sizedtofit_flag == NO) {
		_savedRightEdgeX = frame.origin.x;
		[self realignText];
	}
}

-(void)setText:(NSString*)text{
	[super setText:text];
	[self realignText];
}

-(void)realignText{
	CGRect oldFrame = [self frame];
	
	_sizedtofit_flag = YES;
	[self sizeToFit]; // shrink down size so I can right align it
	
	CGRect newFrame = [self frame];
	
	oldFrame.origin.x = _savedRightEdgeX - newFrame.size.width;
	oldFrame.size.width = newFrame.size.width;
	[super setFrame:oldFrame];
	_sizedtofit_flag = NO;
	
}

@end


@implementation SearchChooseView

- (id)initWithFrame:(struct CGRect)rect {
	
	self = [super initWithFrame:rect];
	
	_rect = rect;
	
	_stateArr = [[NSMutableArray alloc] init];
	
	[_tableCells release];
	_tableCells = [[NSMutableArray alloc] init];
	
	[_tableHeaders release];	
	_tableHeaders = [[NSMutableArray alloc] init];
	
	NSMutableDictionary* cellDict = [[NSMutableDictionary alloc] initWithCapacity:2];
	
	NSString *countstr = [[_delegate getBdo] getCountry];
	NSString *tableheaderstr = [[countstr stringByAppendingString:@" - "] stringByAppendingString:_city];
	
	[cellDict setObject:tableheaderstr forKey:@"title"];
	[cellDict setObject:[[NSNumber alloc] initWithInt:0] forKey:@"beginRow"];
	
	[_tableHeaders addObject: cellDict];
	[cellDict release];
	
	DataManager *dm = [DataManager alloc];
	
	SQLiteDB *sql = [[SQLiteDB alloc] initWithPath:[dm getDataBaseName:countstr]];
	
	[dm release];
	
	
	
	
	NSArray *nsa = [sql query:[NSString stringWithFormat:@"select c.city, s.state from city c, states s, relations r where r.cityid = c.id and r.stateid = s.id and r.cityid = c.id and c.city like '%@' group by c.city, s.state order by c.city, s.state;",_city]];
	//NSLog(@"array: %@",nsa);
	[sql release];
	
	int i=0;
	int count = 0;
	for (i=0;i<[nsa count];i++) {
		
		
		UIImageAndTextTableCell* cell = [[UIImageAndTextTableCell alloc] init];
		[cell setTitle: [[[nsa objectAtIndex:i] objectForKey:@"city"] capitalizedString]];
		[cell setDisclosureStyle:2];
		[cell setShowDisclosure:YES animated:NO];
		
		
		UIRightTextLabel *stateLable = [[UIRightTextLabel alloc] initWithFrame:CGRectMake(290.0f, 16.0f, 200.0f, 15.0f)];
		[stateLable setText:[[nsa objectAtIndex:i] objectForKey:@"state"]];
		
		[_stateArr addObject:[[nsa objectAtIndex:i] objectForKey:@"state"]];
		
		struct __GSFont* font = [NSClassFromString(@"WebFontCache") createFontWithFamily:@"Helvetica" traits:0 size:13];
		float transparent[4] = {0, 0, 0, 0};
		[stateLable setBackgroundColor: CGColorCreate(CGColorSpaceCreateDeviceRGB(), transparent)];
		[stateLable setWrapsText:YES];
		[stateLable setFont:font];
		[stateLable realignText];
		[cell addSubview:stateLable];
		[stateLable release];
		[_tableCells addObject: cell]; 
		[cell release];
		count++;
		
	}
	
	
	_sectionList = [[UISectionList alloc] initWithFrame:CGRectMake(_rect.origin.x, _rect.origin.y, _rect.size.width, _rect.size.height-50.0f) showSectionIndex:NO];
	[_sectionList setDataSource:self];
	
	
	_table = [_sectionList table];
	[_table setShouldHideHeaderInShortLists:NO];
	UITableColumn * packageColumn = [[UITableColumn alloc] initWithTitle:@"Title" identifier:@"title" width:320.0f];
	
	[_table addTableColumn:packageColumn];
	[_table setSeparatorStyle:1];
	[_table setRowHeight:48.0f];
	[_table setDelegate:self];
	[_table setAllowsReordering:NO];
	[_table reloadData];
	[_sectionList reloadData];
	
	
	
	[packageColumn release];
	
	[self addSubview:_sectionList];
	[_sectionList reloadData];
	
	
	
	
}

-(void)setDelegate:(id)del {
	//NSLog(@"delegate: %@",del);
	_delegate = del;
}

-(void)setPrevView:(UIView*)pv {
	_prevView = pv;
}

-(UIView*)getPrevView {
	return _prevView;
}

-(void)setCity:(NSString*)city {
	_city = city;
}

#pragma mark - delegated methods -


- (int)numberOfSectionsInSectionList:(UISectionList *)aSectionList {
	return [_tableHeaders count];
}

- (NSString *)sectionList:(UISectionList *)aSectionList titleForSection:(int)row {	
	return [[_tableHeaders objectAtIndex:row] objectForKey:@"title"];
}       

- (int)sectionList:(UISectionList *)aSectionList rowForSection:(int)row {
	// this is what determines the placement of the header
	return [[[_tableHeaders objectAtIndex:row] valueForKey:@"beginRow"] intValue];
}

- (UITableCell*) table: (UISectionTable*)table cellForRow: (int)row column: (int)col
{
	return [_tableCells objectAtIndex: row];
}

- (UITableCell*) table: (UISectionTable*)table cellForRow: (int)row column: (int)col
			   reusing: (BOOL) reusing
{
	//What does this message do?
    return nil;
}

- (int) numberOfRowsInTable: (UISectionTable*)table
{
	return [_tableCells count];
}

- (void) tableRowSelected: (NSNotification*) notification 
{
	//Get selected cell and filename
	UIImageAndTextTableCell* selectedCell = [_tableCells objectAtIndex: [_table selectedRow]];
	//NSLog(@"seletedCell title: %@",[selectedCell title]);
	
	[_delegate showSearchNameResult: [selectedCell title] withState:[_stateArr objectAtIndex: [_table selectedRow]] withBdo:[_delegate getBdo]];
	
	
	//Do stuff here...
	
	
}



@end




@implementation SearchCountryView

- (id)initWithFrame:(struct CGRect)rect {
	
	self = [super initWithFrame:rect];
	_rect = rect;
	_navBar  = [[UINavigationBar alloc] init];
	[_navBar setFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, 48.0f)];
	[_navBar setDelegate:self];
	[_navBar enableAnimation];
	
	[_navBar pushNavigationItem: [[UINavigationItem alloc] initWithTitle: @"Search"]];	
	
	[self addSubview:_navBar];
	
	_transitionView =  [ [ UITransitionView alloc ] 
						initWithFrame:
						CGRectMake(rect.origin.x, rect.origin.y+48.0f, rect.size.width,
								   rect.size.height - 49.0f)
						];
	[self addSubview:_transitionView];
	[_tableCells release];
	_tableCells = [[NSMutableArray alloc] init];
	
	[_tableHeaders release];	
	_tableHeaders = [[NSMutableArray alloc] init];
	
	NSMutableDictionary* cellDict = [[NSMutableDictionary alloc] initWithCapacity:2];
	[cellDict setObject:@"Countries" forKey:@"title"];
	[cellDict setObject:[[NSNumber alloc] initWithInt:0] forKey:@"beginRow"];
	
	[_tableHeaders addObject: cellDict];
	
	DataManager *dm = [DataManager alloc];
	
	NSArray *installedCountries = [dm getInstalledCountries];
	
	[dm release];
	
	
	int i=0;
	for (i=0;i<[installedCountries count];i++) {	
		UIImageAndTextTableCell* cell = [[UIImageAndTextTableCell alloc] init];
		[cell setTitle: [installedCountries objectAtIndex:i]];
		[cell setDisclosureStyle:2];
		[cell setShowDisclosure:YES animated:NO];
		[_tableCells addObject: cell]; 
		[cell release];
	}	
	
	
	_sectionList = [[UISectionList alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height) showSectionIndex:NO];
	[_sectionList setDataSource:self];
	[_sectionList reloadData];
	[_transitionView transition:0  toView:_sectionList];
	
	
	_table = [_sectionList table];
	[_table setShouldHideHeaderInShortLists:NO];
	UITableColumn * packageColumn = [[UITableColumn alloc] initWithTitle:@"Title" identifier:@"title" width:320.0f];
	
	[_table addTableColumn:packageColumn];
	[_table setSeparatorStyle:1];
	[_table setRowHeight:48.0f];
	[_table setDelegate:self];
	[_table setAllowsReordering:NO];
	
	
	_actualView = _sectionList;
	
	
	_kb = [[UIKeyboard alloc] initWithFrame: CGRectMake(0.0f,245.0f + 216.0f,320.0f,216.0f)];	
	[self addSubview: _kb];
	
	[_bdo release];
	_bdo = [[BrowseDataObject alloc] init];
	
	
	return self;
}

-(void)dealloc {
	[_tableHeaders release];
	[_tableCells release];
	[_sectionList release];	
	[_navBar release];
	
	[_kb release];
	
	[_transitionView release];
	
	[super dealloc];
}

-(UINavigationBar*)getNavBar {
	return _navBar;
}

-(BrowseDataObject*)getBdo {
	return _bdo;
}

-(void)setDelegate:(id)del {
	//NSLog(@"delegate: %@",del);
	_delegate = del;
}

-(UITransitionView*)getTransitionView {
	return _transitionView;
}

- (void) showSearchZipResult:(NSString*)searchentry withState:(NSString*) state withBdo:(BrowseDataObject*)bdo {
	
	[_searchZipResultView release];
	_searchZipResultView = [SearchZipResultView alloc];
	
	//[_bdo setCountry:[selectedCell title]];
	
	[_searchZipResultView setZipcode:searchentry];
	[_searchZipResultView setCountry:[bdo getCountry]];
	[_searchZipResultView setState:state];
	
	[_searchZipResultView setDelegate:self];
	[_searchZipResultView setPrevView:_searchview];
	//[_searchNameResultView setCity:searchentry];
	[_searchZipResultView initWithFrame: CGRectMake(_rect.origin.x, _rect.origin.y
													, _rect.size.width,
													_rect.size.height - 49.0f) ];
	//_previousView = [_actualView retain];
	_actualView = _searchZipResultView;
	if (keyboardVisible) {
		[self hideKeyboard];
	}
	[_navBar showLeftButton:@"Back" withStyle:2 rightButton:nil withStyle:0]; 
	
	
	[_transitionView transition:1 toView:_searchZipResultView];
	[_searchZipResultView fetchData];
	
	
}

- (void) showSearchNameResult:(NSString*)searchentry withState:(NSString*) state withBdo:(BrowseDataObject*)bdo {
	
	[_searchNameResultView release];
	_searchNameResultView = [SearchNameResultView alloc];
	
	//[_bdo setCountry:[selectedCell title]];
	
	[_searchNameResultView setCity:searchentry];
	[_searchNameResultView setCountry:[bdo getCountry]];
	[_searchNameResultView setState:state];
	
	[_searchNameResultView setDelegate:self];
	[_searchNameResultView setPrevView:_searchview];
	//[_searchNameResultView setCity:searchentry];
	[_searchNameResultView initWithFrame: CGRectMake(_rect.origin.x, _rect.origin.y
													 , _rect.size.width,
													 _rect.size.height - 49.0f) ];
	//_previousView = [_actualView retain];
	_actualView = _searchNameResultView;
	if (keyboardVisible) {
		[self hideKeyboard];
	}
	[_navBar showLeftButton:@"Back" withStyle:2 rightButton:nil withStyle:0]; 
	
	
	[_transitionView transition:1 toView:_searchNameResultView];
	[_searchNameResultView fetchData];
	
	
}

- (void) showSearchChooser:(NSString*)searchentry withBdo:(BrowseDataObject*)bdo {
	
	[_searchChooseView release];
	_searchChooseView = [SearchChooseView alloc];
	
	//[_bdo setCountry:[selectedCell title]];
	
	[_searchChooseView setDelegate:self];
	[_searchChooseView setPrevView:_searchview];
	[_searchChooseView setCity:searchentry];
	[_searchChooseView initWithFrame: CGRectMake(_rect.origin.x, _rect.origin.y
												 , _rect.size.width,
												 _rect.size.height - 49.0f) ];
	//_previousView = [_actualView retain];
	_actualView = _searchChooseView;
	if (keyboardVisible) {
		[self hideKeyboard];
	}
	[_navBar showLeftButton:@"Back" withStyle:2 rightButton:nil withStyle:0]; 
	
	
	[_transitionView transition:1 toView:_searchChooseView];
	
}

-(void)keyboardReturnPressed {
	keyboardVisible = NO;
	[self hideKeyboard];
	[_navBar showLeftButton:@"Back" withStyle:2 rightButton:@"Keypad" withStyle:0];
}

- (void) clearButtonClicked {
	
	if (!keyboardVisible) {
		keyboardVisible = YES;
		[self showKeyboard];
		[_navBar showLeftButton:@"Back" withStyle:2 rightButton:@"Keypad" withStyle:1];
		
		
	}
	
}

-(void)showKeyboard {
	
	CGRect startFrame;
	CGRect endFrame;
	
	
	NSMutableArray *animations = [[NSMutableArray alloc] init];
	
	
	startFrame = CGRectMake(0., 245.0 + 216.0, 320., 216.);
	endFrame = startFrame;
	endFrame.origin.y = 245.0;
	
	[_kb setFrame:startFrame];
	
	CGRect startFrame1;
	CGRect endFrame1;
	
	startFrame1 = CGRectMake(0.0f, 411.0f, 320.0f, 49.0f);
	endFrame1 = startFrame1;
	endFrame1.origin.y = 411.0+49.0f;
	
	
	CGRect startFrame2;
	CGRect endFrame2;
	
	startFrame2 =  CGRectMake(0.0, 35.0, 320.0, 165.0 + 165.0);
	endFrame2 =  startFrame2;
	endFrame2.size.height -= 165.0;
	
	if (_actualView == _searchview) [[_actualView getSearchTable] setFrame:startFrame2];
	
	[[_delegate getButtonBar] setFrame:startFrame1];
	
	UIFrameAnimation *buttonBarAnimation = [[UIFrameAnimation alloc] initWithTarget:[_delegate getButtonBar]];
	[buttonBarAnimation setStartFrame:startFrame1];
	[buttonBarAnimation setEndFrame:endFrame1];
	[buttonBarAnimation setSignificantRectFields:2];
	[buttonBarAnimation setDelegate:self];
	[animations addObject:buttonBarAnimation];
	[buttonBarAnimation release];
	
	
	
	UIFrameAnimation *keyboardAnimation = [[UIFrameAnimation alloc] initWithTarget:_kb];
	[keyboardAnimation setStartFrame:startFrame];
	[keyboardAnimation setEndFrame:endFrame];
	[keyboardAnimation setSignificantRectFields:2];
	[keyboardAnimation setDelegate:self];
	[animations addObject:keyboardAnimation];
	
	[keyboardAnimation release];
	
	if (_actualView == _searchview) {
		UIFrameAnimation *searchTableAnimation = [[UIFrameAnimation alloc] initWithTarget:[_actualView getSearchTable]];
		[searchTableAnimation setStartFrame:startFrame2];
		[searchTableAnimation setEndFrame:endFrame2];
		[searchTableAnimation setSignificantRectFields:8];
		[searchTableAnimation setDelegate:self];
		[animations addObject:searchTableAnimation];
		[searchTableAnimation release];
	}
	
	
	
	[[UIAnimator sharedAnimator] addAnimations:animations withDuration:.5 start:YES];
	
	if (_actualView == _searchview) { 
		[[_actualView getSearchTable] setRowHeight:36.0f];
		[[_actualView getSearchTable] reloadData];
	}	
	
}

-(void) hideKeyboard {
	
	CGRect startFrame;
	CGRect endFrame;
	NSMutableArray *animations = [[NSMutableArray alloc] init];
	
	startFrame = CGRectMake(0., 245.0, 320., 216.);
	endFrame = startFrame;
	endFrame.origin.y = 245.0 + 216.;
	
	[_kb setFrame:startFrame];
	
	CGRect startFrame1;
	CGRect endFrame1;
	
	startFrame1 = CGRectMake(0.0f, 411.0f+49.0f, 320.0f, 49.0f);
	endFrame1 = startFrame1;
	endFrame1.origin.y = 411.0;
	
	
	CGRect startFrame2;
	CGRect endFrame2;
	
	startFrame2 =  CGRectMake(0.0, 35.0, 320.0, 165.0);
	endFrame2 =  startFrame2;
	endFrame2.size.height += 165.0;
	
	
	if (_actualView == _searchview) { [[_actualView getSearchTable] setFrame:startFrame2]; }
	
	[[_delegate getButtonBar] setFrame:startFrame1];
	
	UIFrameAnimation *buttonBarAnimation = [[UIFrameAnimation alloc] initWithTarget:[_delegate getButtonBar]];
	[buttonBarAnimation setStartFrame:startFrame1];
	[buttonBarAnimation setEndFrame:endFrame1];
	[buttonBarAnimation setSignificantRectFields:2];
	[buttonBarAnimation setDelegate:self];
	[animations addObject:buttonBarAnimation];
	[buttonBarAnimation release];
	
	UIFrameAnimation *keyboardAnimation = [[UIFrameAnimation alloc] initWithTarget:_kb];
	[keyboardAnimation setStartFrame:startFrame];
	[keyboardAnimation setEndFrame:endFrame];
	[keyboardAnimation setSignificantRectFields:2];
	[keyboardAnimation setDelegate:self];
	[animations addObject:keyboardAnimation];
	[keyboardAnimation release];
	
	
	if (_actualView == _searchview) { 
		UIFrameAnimation *searchTableAnimation = [[UIFrameAnimation alloc] initWithTarget:[_actualView getSearchTable]];
		[searchTableAnimation setStartFrame:startFrame2];
		[searchTableAnimation setEndFrame:endFrame2];
		[searchTableAnimation setSignificantRectFields:8];
		[searchTableAnimation setDelegate:self];
		[animations addObject:searchTableAnimation];
		[searchTableAnimation release];
		
	}
	
	
	
	[[UIAnimator sharedAnimator] addAnimations:animations withDuration:.5 start:YES];
	
	
	if (_actualView == _searchview) { 
		[[_actualView getSearchTable] setRowHeight:48.0f];
		[[_actualView getSearchTable] reloadData];
	}	
	
}


#pragma mark - delegated methods -

- (void)navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button {
	switch (button) {
		case 0:
			if (keyboardVisible) {
				//	[_kb removeFromSuperview];
				[self hideKeyboard];
				keyboardVisible = NO;
				[_navBar showLeftButton:@"Back" withStyle:2 rightButton:@"Keypad" withStyle:0]; 
			} else {
				//	[self addSubview: _kb];
				
				[self showKeyboard];
				
				keyboardVisible = YES;
				[_navBar showLeftButton:@"Back" withStyle:2 rightButton:@"Keypad" withStyle:1]; 
			}
			break;
			case 1:
			if ([_actualView getPrevView] == _sectionList) {
				[_navBar showLeftButton:nil withStyle:2 rightButton:nil withStyle:0];
			}
			
			if (_actualView  == _searchChooseView || _actualView == _searchNameResultView || _actualView == _searchZipResultView) {
				//NSLog(@"fromView: searchChooseView");
				
				if (keyboardVisible) {
					[self showKeyboard];
					[_navBar showLeftButton:@"Back" withStyle:2 rightButton:@"Keypad" withStyle:1]; 
					
				} else {
					[_navBar showLeftButton:@"Back" withStyle:2 rightButton:@"Keypad" withStyle:0]; 
				}
			} else {
				
				if (keyboardVisible) {
					[self hideKeyboard];
				}
			}
			[_transitionView transition:2 fromView:_actualView toView:[_actualView getPrevView]];
			
			_actualView = [_actualView getPrevView];
			
			
			
			break;
	}
}

- (int)numberOfSectionsInSectionList:(UISectionList *)aSectionList {
	return [_tableHeaders count];
}

- (NSString *)sectionList:(UISectionList *)aSectionList titleForSection:(int)row {	
	return [[_tableHeaders objectAtIndex:row] objectForKey:@"title"];
}       

- (int)sectionList:(UISectionList *)aSectionList rowForSection:(int)row {
	// this is what determines the placement of the header
	return [[[_tableHeaders objectAtIndex:row] valueForKey:@"beginRow"] intValue];
}

- (UITableCell*) table: (UISectionTable*)table cellForRow: (int)row column: (int)col
{
	return [_tableCells objectAtIndex: row];
}

- (UITableCell*) table: (UISectionTable*)table cellForRow: (int)row column: (int)col
			   reusing: (BOOL) reusing
{
	//What does this message do?
    return nil;
}

- (int) numberOfRowsInTable: (UISectionTable*)table
{
	return [_tableCells count];
}

- (void) tableRowSelected: (NSNotification*) notification 
{
	//Get selected cell and filename
	UIImageAndTextTableCell* selectedCell = [_tableCells objectAtIndex: [_table selectedRow]];
	//NSLog(@"seletedCell title: %@",[selectedCell title]);
	
	//[_transitionView transition:1 toView:namezipview];
	/*
	 SQLiteDB *sql = [[SQLiteDB alloc] initWithPath:@"/Applications/ZIPcodes.app/germany.dat"];
	 
	 NSArray *nsa = [sql query:@"SELECT * from states ORDER BY state asc;"];
	 NSLog(@"array: %@",nsa);
	 [sql release];
	 */
	//Do stuff here...
	
	[_bdo setCountry:[selectedCell title]];
	
	
	_searchview = [SearchView alloc];
	
	//[_bdo setCountry:[selectedCell title]];
	
	[_searchview setDelegate:self];
	[_searchview setPrevView:_sectionList];
	[_searchview initWithFrame: CGRectMake(_rect.origin.x, _rect.origin.y
										   , _rect.size.width,
										   _rect.size.height) ];
	//_previousView = [_actualView retain];
	_actualView = _searchview;
	
	[_transitionView transition:1 toView:_searchview];
	//[_searchview release];
	
	[self showKeyboard];
	
	keyboardVisible = YES;
	
	
	
}



@end



@implementation SearchField

-(id)initWithFrame:(CGRect)frame
{
	self = [super initWithFrame:frame];
	
	return self;
}

- (bool)isEditing {
	
	[_delegate isEdited];
	[super isEditing];
	
}

-(void)_clearButtonClicked:(id)p {
	[_delegate clearButtonClicked];
	[super _clearButtonClicked:p];
}

- (void)mouseDown:(struct __GSEvent *)fp8 {
	//NSLog(@"mousedown");
	[_delegate clearButtonClicked];
	[super mouseDown:fp8];
}

@end






@implementation SearchView

-(id)initWithFrame:(CGRect)rect
{
	
	self = [super initWithFrame:rect];
	
	
	
	[[_delegate getNavBar] showLeftButton:@"Back" withStyle:2 rightButton:@"Keypad" withStyle:1];	
	
	_textView = [[UINavigationBar alloc] init];
	[_textView setFrame:CGRectMake(0.0f, 0.0f, 320.0f, 35.0f)];
	[self addSubview:_textView];
	
	struct __GSFont* font = [NSClassFromString(@"WebFontCache") createFontWithFamily:@"Helvetica" traits:0 size:16];
	_searchField = [[SearchField alloc] initWithFrame: CGRectMake(0.0f, 2.0f, 320.0f, 30.0f)];
	[_searchField setFont:font];
	[_searchField setClearButtonStyle:2];
	[_searchField setText:@""];
	//[_searchField drawText:CGRectMake(0.0f, 1.0f, 320.0f, 30.0f)];
	[_searchField setPaddingBottom:1.0f];
	[_searchField setPaddingTop:5.0f];
	[_searchField setDelegate:self];	
	[[_searchField textTraits] setEditingDelegate:self];
	//[searchField setTextAutorresizesToFit:YES];
	//[_searchField setVerticallyCenterText:NO];
	
	_uip = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(270, 7, 20,20)];
	[_uip setStyle:1];
	//[_uip stopAnimation];
	
	
	
	//_kb = [[UIKeyboard alloc] initWithFrame: CGRectMake(0.0f,245.0f,320.0f,216.0f)];	
	[_searchField setAutoCapsType:0];
	[_searchField setAutoCorrectionType:1];
	[_searchField setReturnKeyType:4];
	[_searchField setPreferredKeyboardType: 8];
	[_searchField setAutoEnablesReturnKey:YES];
	
	[self addSubview:_navBar];
	[self addSubview:_searchField];
	//	[searchField setNeedsDisplay];
	//NSLog(@"%@",[searchField text]);
	[_searchField becomeFirstResponder];
	//[self buildTable];
	//NSLog(@"buttonbar: %@",[_delegate getButtonBar]);
	//[[_delegate getButtonBar] setFrame:CGRectMake(0.0f, 411.0f+49.0f, 320.0f, 49.0f)];
	//	[self addSubview: _kb];
	
	_table = [[UITable alloc] initWithFrame: CGRectMake(0.0f, 35.0f, 320.0f, 165.0f)];
	
	UITableColumn * packageColumn = [[UITableColumn alloc] initWithTitle:@"Title" identifier:@"title" width:320.0f];
	
	[_table addTableColumn:packageColumn];
	[_table setSeparatorStyle:2];
	[_table setRowHeight:36.0f];
	[_table setDelegate:self];
	[_table setDataSource: self];
	[packageColumn release];
	
	
	//[self fillTable];
	//	cellDict = [[NSMutableDictionary alloc] initWithCapacity:2];
	//[cellDict setObject:@"B" forKey:@"title"];
	//[cellDict setObject:[[NSNumber alloc] initWithInt:10] forKey:@"beginRow"];
	
	//[_tableHeaders addObject: cellDict];
	
	//Refresh the fileview table
	
	_tableCells = [[NSMutableArray alloc] init];
	
	[self addSubview:_table];
	[self addSubview:_uip];
	
	
	
	
	return self;
}

-(void)dealloc {
	[_navBar release];
	[_textView release];
	
	[_searchField release];
	[_uip release];
	[super dealloc];
	
}

- (void) fillTable {
	
	
	DataManager *dm = [DataManager alloc];
	NSString *countstr = [[_delegate getBdo] getCountry];
	//NSLog(@"bdo: %@",[_delegate getBdo]);
	SQLiteDB *sql = [[SQLiteDB alloc] initWithPath:[dm getDataBaseName:countstr]];
	
	[dm release];
	
	NSArray *nsa;
	
	if (![self stringContainsNumbers:_lastText]) {
		nsa = [sql query:[NSString stringWithFormat:@"SELECT city AS output from city where city like '%@%%' group by city ORDER BY city asc LIMIT 100;",_lastText]];
	} else {
		nsa = [sql query:[NSString stringWithFormat:@"SELECT zipcode AS output from zipcodes where zipcode like '%@%%' group by zipcode ORDER BY zipcode asc LIMIT 100;",_lastText]];
	}		
	//NSLog(@"array: %@",nsa);
	[sql release];
	
	[_tableCells release];
	_tableCells = [[NSMutableArray alloc] init];
	
	int i=0;
	for (i = 0;i < [nsa count];i++) {
		
		//NSLog(@"cell: %@",[[nsa objectAtIndex:i] objectForKey:@"city"]);
		UIImageAndTextTableCell* cell = [[UIImageAndTextTableCell alloc] init];
		[cell setTitle:[[[nsa objectAtIndex:i] objectForKey:@"output"] capitalizedString]];
		[cell setDisclosureStyle:2];
		[cell setShowDisclosure:YES animated:NO];
		[_tableCells addObject: cell]; 
		[cell release];
		
	}
	
	if ([nsa count] == 100) {
		
		struct __GSFont* font = [NSClassFromString(@"WebFontCache") createFontWithFamily:@"Helvetica" traits:0 size:11];
		UIImageAndTextTableCell* cell = [[UIImageAndTextTableCell alloc] init];
		UITextLabel *moreView = [[UITextLabel alloc] initWithFrame:CGRectMake(20.0f, 0.0f, 320.0f, 30.0f)];
		[moreView setText:@"More than 100 entries found - please narrow your search!"];
		[moreView setFont:font];
		[cell setTitle:@""];
		[cell addSubview:moreView];
		[cell setEnabled:NO];
		//		[cell setDisclosureStyle:2];
		[cell setShowDisclosure:NO animated:NO];
		[_tableCells addObject: cell]; 
		[cell release];
	}
	
	[_table reloadData];
	[_uip stopAnimation];
}

- (void) showUIP:(id)p {
	
}

- (BOOL)stringContainsNumbers:(NSString *)str {
	BOOL hasNumbers = NO;
	
	NSCharacterSet *characters = [NSCharacterSet decimalDigitCharacterSet];
	NSRange range = [str rangeOfCharacterFromSet:characters];
	
	if (range.location != NSNotFound) {
		hasNumbers = YES;
	}
	
	return hasNumbers;
}

- (void) handleInput:(id)p {
	
	//NSLog(@"inputtimer fired, input: %@",_lastText);
	
	
	if ([_lastText isEqual:@""]) {
		[_uip stopAnimation];
		[_tableCells release];
		_tableCells = [[NSMutableArray alloc] init];
		[_table reloadData];
		return;
	}
	
	[self fillTable];
	[_table reloadData];
	
	
}

-(void)clearButtonClicked {
	[_delegate clearButtonClicked];
}

-(void)isEdited
{
	
	
	NSString *searchFldStr = [_searchField text];
	
	if ([searchFldStr isEqual:_lastText]) return;
	
	_lastText = [searchFldStr copy];
	
	[_inputTimer invalidate];
	[_inputTimer release];
	
	[_uip startAnimation];	
	
	_inputTimer = [[NSTimer scheduledTimerWithTimeInterval:0.75 target:self selector:@selector(handleInput:) userInfo:nil repeats:NO] retain];
	
}

-(void)setPrevView:(UIView*)pv {
	_prevView = pv;
}

-(UIView*)getPrevView {
	return _prevView;
}

-(UITable*)getSearchTable {
	return _table;
}

-(void)setDelegate:(id)del {
	//NSLog(@"delegate: %@",del);
	_delegate = del;
}

- (void) processTableSelection:(id)p {
	
	//Get selected cell and filename
	UIImageAndTextTableCell* selectedCell = [_tableCells objectAtIndex: [_table selectedRow]];
	//Do stuff here...
	
	DataManager *dm = [DataManager alloc];
	NSString *countstr = [[_delegate getBdo] getCountry];
	
	SQLiteDB *sql = [[SQLiteDB alloc] initWithPath:[dm getDataBaseName:countstr]];
	
	[dm release];
	
	if (![self stringContainsNumbers:_lastText]) {
		NSArray *nsa = [sql query:[NSString stringWithFormat:@"select c.city, s.state from city c, states s, relations r where r.cityid = c.id and r.stateid = s.id and r.cityid = c.id and c.city like '%@' group by c.city, s.state order by c.city;",[selectedCell title]]];
		//NSLog(@"querycount: %d",[nsa count]);
		if ([nsa count] >1) {
			
			[_delegate showSearchChooser: [selectedCell title] withBdo:[_delegate getBdo]];
		} else {
			[_delegate showSearchNameResult: [selectedCell title] withState:@"%" withBdo:[_delegate getBdo]];
			//NSLog(@"solocount");
		}
	} else {
		[_delegate showSearchZipResult: [selectedCell title] withState:@"%" withBdo:[_delegate getBdo]];		
	}
	[sql release];
	
	
}

#pragma mark - delegated methods -

-(void)keyboardInput:(id)k shouldInsertText:(id)i isMarkedText:(int)b{
	
	if ([i characterAtIndex:0] == 0xA) {
   		//NSLog(@"user return pressed");
		[_delegate keyboardReturnPressed];
	}
}

- (UITableCell*) table: (UISectionTable*)table cellForRow: (int)row column: (int)col
{
	return [_tableCells objectAtIndex: row];
}

- (UITableCell*) table: (UISectionTable*)table cellForRow: (int)row column: (int)col
			   reusing: (BOOL) reusing
{
	//What does this message do?
    return nil;
}

- (int) numberOfRowsInTable: (UISectionTable*)table
{
	return [_tableCells count];
	
}

- (void) tableRowSelected: (NSNotification*) notification 
{
	
	
	[[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(processTableSelection:) userInfo:nil repeats:NO] retain];
	
	
	
	
}


@end
